﻿function AzureOnlineTableColumnsView() {

    var self = this;

    var columns = ko.observableArray([]);

    var selected = ko.computed(function () {
        var cols = columns();
        var res = [];
        for (var i = 0; i < cols.length; i++) {
            var col = cols[i];
            if (col.selected()) {
                res.push(col);
            }
        }
        return res;
    });

    var settings;

    function getHtmlId(col) {
        return 'tableColumns-' + utils.getHashCode(col.name());
    }

    function arrayToObject(array) {
        var obj = {};
        for (var i = 0; i < array.length; i++) {
            obj[array[i]] = true;
        }
        return obj;
    }

    function init(allColumns, tableSettings) {
        settings = tableSettings;

        allColumns = allColumns.slice(0);

        var hiddenColumns = tableSettings.getObject('hiddenColumns');
        if (hiddenColumns) {
            hiddenColumns = arrayToObject(hiddenColumns);
        }

        var cols = [];
        for (var i = 0; i < allColumns.length; i++) {
            var col = new AzureOnlineTableColumnView();
            var name = allColumns[i];
            col.name(name);
            col.selected(!hiddenColumns || !hiddenColumns[name]);
            cols.push(col);
        }
        columns(cols);
    }

    function save() {
        var cols = columns();
        var res = [];
        for (var i = 0; i < cols.length; i++) {
            var col = cols[i];
            if (!col.selected()) {
                res.push(col.name());
            }
        }
        if (settings) {
            settings.setObject('hiddenColumns', res);
        }
    }

    function reset() {
        var cols = columns();
        for (var i = 0; i < cols.length; i++) {
            var col = cols[i];
            col.selected(true);
        }
    }

    self.init = init;
    self.columns = columns;
    self.selected = selected;
    self.getHtmlId = getHtmlId;
    self.save = save;
    self.reset = reset;
}


function AzureOnlineTableColumnView() {

    this.name = ko.observable('');

    this.selected = ko.observable(true);
}